package com.why.controller;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.util.StringUtil;
import com.why.pojo.Product;
import com.why.pojo.User;
import com.why.service.ProductService;
import com.why.utils.FtpUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class ProductController {

    @Autowired
    ProductService productService;

    @Autowired
    private SolrClient solrClient;

    //根据分类ID查询所有商品，并进行分页查询
    @RequestMapping(value = "catelist",produces = "application/json;charset=utf-8")
    public PageInfo<Product> cateList(Integer categoryLevelId,Integer pageNum,Integer pageSize){
        return productService.productList(categoryLevelId, pageNum, pageSize);
    }

    //根据id查找商品
    @RequestMapping(value = "product",produces = "application/json;charset=utf-8")
    public String productDetails(Integer productId){
        Product product = productService.selectByPrimaryKey(productId);
        return JSON.toJSONString(product);
    }

    //根据商品名称进行solr查询
    @RequestMapping(value = "/selectProductBySolr",produces = "application/json;charset=utf-8")
    public Object selectProductBySolr(String name,Integer pageNum,Integer pageSize,Integer status) throws IOException, SolrServerException {
        if (status==0){
            name= new String(name.getBytes("ISO8859_1"), "UTF-8");
        }
        SolrQuery query = new SolrQuery();
        query.addSort("price_f", SolrQuery.ORDER.desc);
        query.setQuery("name_ik:"+name);
        query.addFilterQuery("isdelete_i:[0 TO 0]");
        query.setStart((pageNum-1)*pageSize);
        query.setRows(pageSize);

        query.setHighlight(true);
        query.addHighlightField("name_ik");
        query.setHighlightSimplePre("<font style=\"color:red\">");
        query.setHighlightSimplePost("</font>");

        QueryResponse qr = solrClient.query(query);

        int[] navigatepageNums;

        long numFound = qr.getResults().getNumFound();
        long pages=numFound%pageSize==0?numFound/pageSize:(numFound/pageSize)+1;
        //当总页数小于或等于导航页码数时
        if (pages <= 5) {
            navigatepageNums = new int[(int) pages];
            for (int i = 0; i < pages; i++) {
                navigatepageNums[i] = i + 1;
            }
        } else { //当总页数大于导航页码数时
            navigatepageNums = new int[5];
            int startNum = pageNum - 5 / 2;
            int endNum = pageNum + 5 / 2;

            if (startNum < 1) {
                startNum = 1;
                //(最前pageNum页
                for (int i = 0; i < 5; i++) {
                    navigatepageNums[i] = startNum++;
                }
            } else if (endNum > pages) {
                endNum = (int) pages;
                //最后pageNum页
                for (int i = 5 - 1; i >= 0; i--) {
                    navigatepageNums[i] = endNum--;
                }
            } else {
                //所有中间页
                for (int i = 0; i < 5; i++) {
                    navigatepageNums[i] = startNum++;
                }
            }
        }

        List<Product> list = qr.getBeans(Product.class);
        Map<String, Map<String, List<String>>> map = qr.getHighlighting();

        for (Product product:list){
            product.setName(map.get(product.getId()).get("name_ik").get(0));
        }

        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("name",name);
        hashMap.put("list",list);
        hashMap.put("count",pages);
        hashMap.put("pageNum",(pageNum-1)*pageSize);
        hashMap.put("pageSize",pageSize);
        hashMap.put("navigatepageNums",navigatepageNums);
        hashMap.put("numFound",numFound);

        return JSON.toJSONString(hashMap);
    }

    //分页查询所有商品
    @RequestMapping("/selectAllProduct")
    public PageInfo<Product> selectAllProduct(Integer pageNum,Integer pageSize){
        return productService.selectAllProduct(pageNum, pageSize);
    }

    //下架商品
    @RequestMapping("/deleteProduct")
    public String deleteProduct(Integer id) throws IOException, SolrServerException {
        if (productService.deleteProduct(id)){
            return "success";
        }
        return "failed";
    }

    //新增商品
    @RequestMapping("/addProduct")
    public String addProduct(MultipartFile imgs,Product product) throws IOException, SolrServerException {
        //获取上传的文件流
        InputStream inputStream=imgs.getInputStream();
        //获取上传的文件名
        String fileName=imgs.getOriginalFilename();
        System.out.println(fileName);
        //截取后缀
        String suffix=fileName.substring(fileName.lastIndexOf("."));
        //使用时间戳拼接后缀，生成一个不重复的文件名
        String newFileName=System.currentTimeMillis()+suffix;

        product.setFilename(newFileName);
        //调用自定义的FTP工具类上传文件
        boolean b = FtpUtil.uploadFile(newFileName, inputStream);
        if (b){
            if (productService.insertSelective(product)){
                return "success";
            }
        }else {
            return "error";
        }
        return "failed";
    }

    //修改商品
    @RequestMapping("/updateProduct")
    public String updateProduct(MultipartFile imgs,Product product) throws IOException, SolrServerException {
        String oldFileName=imgs.getOriginalFilename();

        if (oldFileName!=null && !oldFileName.equals("")){
            //获取上传的文件流
            InputStream inputStream=imgs.getInputStream();
            //获取上传的文件名
            String fileName=imgs.getOriginalFilename();
            System.out.println(fileName);
            //截取后缀
            String suffix=fileName.substring(fileName.lastIndexOf("."));
            //使用时间戳拼接后缀，生成一个不重复的文件名
            String newFileName=System.currentTimeMillis()+suffix;

            product.setFilename(newFileName);
            //调用自定义的FTP工具类上传文件
            boolean b = FtpUtil.uploadFile(newFileName, inputStream);
            if (b){
                if (productService.updateByPrimaryKeySelective(product)){
                    return "success";
                }
            }
            return "error";
        }else {
            if (productService.updateByPrimaryKeySelective(product)){
                return "success";
            }
        }
        return "failed";
    }

    //上架商品
    @RequestMapping("/putaway")
    public String putaway(Integer id) throws IOException, SolrServerException {
        if (productService.putaway(id)){
            return "success";
        }
        return "failed";
    }

    //查询商品名称是否唯一
    @RequestMapping("/selectProByName")
    public String selectProByName(String name){
        if (productService.selectProByName(name)==null){
            return "success";
        }
        return "failed";
    }
}
